﻿//-----------------------------------------------------------------------
// <copyright file="ActionRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.EntityClient;
using System.Linq;
using FastNET.CleanAct.Client.ManagerEngineData.Entities;
using FastNET.CleanAct.Common.Repository;
using FastNET.CleanAct.Common.Repository.Interfaces.DataInterfaces.ManagementEngine;
using FastNET.CleanAct.Common.Repository.Interfaces.Repositories.ManagementEngine;

#endregion

namespace FastNET.CleanAct.Client.ManagerEngineData.Repositories
{
    /// <summary>
    /// General repository for managing Actions
    /// </summary>
    internal class ActionRepository
        : IActionRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the ActionRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal ActionRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IRepository<IActionData> Members

        /// <summary>
        /// Retrieves all instances of IActionData from the repository
        /// </summary>
        /// <returns>IEnumerable of the requested IData</returns>
        public IList<IActionData> Retrieve()
        {
            List<IActionData> returnValues = new List<IActionData>();

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                IEnumerable<Entities.Action> query = from item in dataSource.Actions select item;

                foreach (Entities.Action item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IActionData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IActionData Retrieve(Identity ID)
        {
            if (!ID.CanFitInGuid())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Guid Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            Guid searchID = ID;

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                Entities.Action foundItem = (from
                                                item
                                                in
                                                 dataSource.Actions
                                             where
                                                 item.ActionID == searchID
                                             select
                                                 item).FirstOrDefault();

                if (foundItem != null)
                {
                    dataSource.Detach(foundItem);
                }

                return foundItem;
            }
        }

        /// <summary>
        /// Deletes the requested IActionData
        /// </summary>
        /// <param name="Data">IActionData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IActionData is new or already deleted</exception>
        public void Delete(IActionData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Entities.Action))
            {
                throw new InvalidCastException("Data is not of type Action. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                dataSource.Attach((Entities.Action)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IActionData
        /// </summary>
        /// <param name="Data">IActionData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IActionData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Entities.Action))
            {
                throw new InvalidCastException("Data is not of type Action. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToActions((Entities.Action)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    object originalItem;

                    // Create the detached object's entity key.
                    EntityKey itemKey = dataSource.CreateEntityKey("Actions", Data);

                    // Get the original item based on the entity key from the context
                    // or from the database.
                    if (dataSource.TryGetObjectByKey(itemKey, out originalItem))
                    {
                        // Call the ApplyPropertyChanges method to apply changes
                        // from the updated item to the original version.
                        dataSource.ApplyPropertyChanges(itemKey.EntitySetName, Data);
                        dataSource.SaveChanges();
                    }
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IActionData
        /// </summary>
        /// <returns>New Instance of IActionData</returns>
        public IActionData Create()
        {
            return new Entities.Action();
        }

        #endregion

        /// <summary>
        /// Retrieves a list of Actions given the associated Template
        /// </summary>
        /// <param name="templateID">Template ID to retrieve by</param>
        /// <returns>IList of IActionData found or null if no items were found</returns>
        public IList<IActionData> RetrieveByTemplateID(Identity templateID)
        {
            List<IActionData> returnItems = new List<IActionData>();

            if (!templateID.CanFitInGuid())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Guid Type. Currently is {0}.", templateID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            Guid searchID = templateID;

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                IEnumerable<Entities.Action> foundItems = (from
                                                item
                                                in
                                                               dataSource.Actions
                                                           where
                                                               item.Template.TemplateID == searchID
                                                           select
                                                               item);

                foreach (Entities.Action item in foundItems)
                {
                    dataSource.Detach(item);
                    returnItems.Add(item);
                }

                return returnItems;
            }
        }
    }
}